package com.osell.selection.ui.product;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.ResultBean;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.imgupload.ChooseImageAvtivity;
import com.da.lon.wang.xlg.util.MyBitmapFactory;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.LoadingDialog;
import com.osell.selection.data.network.RestAPI;
import com.osell.selection.data.network.entity.ResponseData;
import com.osell.selection.ui.base.BaseBottomSheetDialogFragment;

import net.tsz.afinal.http.AjaxParams;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RateFragment extends BaseBottomSheetDialogFragment implements View.OnClickListener, TextWatcher, RatingBar.OnRatingBarChangeListener {

    @BindView(R.id.et_comment)
    EditText et_comment;
    @BindView(R.id.btn_choose_image)
    ImageButton btn_choose_image;
    @BindView(R.id.rb_rating)
    RatingBar rb_rating;
    @BindView(R.id.btn_cancel)
    Button btn_cancel;
    @BindView(R.id.btn_submit)
    Button btn_submit;

    private Unbinder mUnBinder;

    private String mProductId;
    private String mProductNumber;
    private List<String> mImages;

    private Disposable mDisposable;

    private LoadingDialog dialog;

    public static RateFragment newInstance(String productId, String productNumber) {
        RateFragment fragment = new RateFragment();
        Bundle args = new Bundle();
        args.putString("product_id", productId);
        args.putString("product_number", productNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mProductId = args.getString("product_id");
            mProductNumber = args.getString("product_number");
        }
        dialog = new LoadingDialog(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rate, container, false);
        mUnBinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        btn_choose_image.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
        et_comment.addTextChangedListener(this);
        rb_rating.setOnRatingBarChangeListener(this);

        validateInput();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_choose_image:
                startActivityForResult(new Intent(v.getContext(), ChooseImageAvtivity.class).putExtra("only_choose", true), 100);
                break;
            case R.id.btn_cancel:
                dismiss();
                break;
            case R.id.btn_submit:
                customerUpload();
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == Activity.RESULT_OK) {
                mImages = data.getStringArrayListExtra("images");
                validateInput();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnBinder.unbind();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    private void validateInput() {
        if (TextUtils.isEmpty(et_comment.getEditableText())
                || rb_rating.getNumStars() == 0
                || (mImages == null || mImages.isEmpty())) {
            btn_submit.setEnabled(false);
        } else {
            btn_submit.setEnabled(true);
        }
    }

    private void customerUpload() {
        String url = XLGConstants.URL + "Login-yijian";
        HttpLoader<ResultBean> httpLoader = new HttpLoader<>(getContext(), url, ResultBean.class);
        AjaxParams params = new AjaxParams();
        try {
            for (int i = 0; i < mImages.size(); i++) {
                File saveMyBitmap = MyBitmapFactory.saveMyBitmap("compressImage" + i + ".jpg",
                        MyBitmapFactory.getMatrixImage(mImages.get(i)));
                if (saveMyBitmap == null) {
                    continue;
                }
                params.put("file" + i, saveMyBitmap);
            }
            params.put("id", mUserInfoSp.getString("user_id", ""));
            params.put("user_key", mUserInfoSp.getString("user_key", ""));
            params.put("token", XLGDataUtils.encrypt2MD5("Login" + XLGConstants.SECRET + "yijian"));
            params.put("device_type", "1");
            httpLoader.setReplayManagerListener(new HttpLoader.OnWebLoadListenerReplay<ResultBean>() {

                @Override
                public void OnStart() {
                    dialog.show();
                }

                @Override
                public void OnError(String error) {
                    dialog.dismiss();
                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(ResultBean t, String result) {
                    if (t != null) {
                        if (t.getCode().equals("000000")) {
                            if (mDisposable != null) {
                                mDisposable.dispose();
                            }
                            mDisposable = RestAPI.getInstance().oSellService()
                                    .addProductComment(mUserInfoSp.getString("user_id", ""),
                                            mUserInfoSp.getString("user_key", ""),
                                            mProductId, mProductNumber, et_comment.getEditableText().toString(),
                                            rb_rating.getNumStars(), "http://sel.sk.osell.com" + t.getResult().getTopic_img(), mProductNumber)
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Consumer<ResponseData<String>>() {
                                        @Override
                                        public void accept(ResponseData<String> objectResponseData) {
                                            dialog.dismiss();
                                            if (TextUtils.equals("000000", objectResponseData.code)) {
                                                Toast.makeText(MyApplication.getInstance(), objectResponseData.data, Toast.LENGTH_SHORT).show();
                                                dismiss();
                                            } else {
                                                Toast.makeText(MyApplication.getInstance(), objectResponseData.message, Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable throwable) {
                                            dialog.dismiss();
                                        }
                                    });
                        } else {
                            Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

            httpLoader.loadReplayData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        validateInput();
    }

    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        validateInput();
    }
}
